from PyQt5.QtCore import Qt,\
                         QModelIndex,\
                         pyqtSignal,\
                         pyqtSlot
from PyQt5.QtWidgets import QPushButton,\
                            QDialog,\
                            QDialogButtonBox,\
                            QGridLayout,\
                            QLabel,\
                            QLineEdit,\
                            QMessageBox
from PyQt5.QtSql import     QSqlQuery, QSqlRecord

class AddDialog(QDialog):
    added = pyqtSignal(str, str)

    def __init__(self, parent, model):
        super().__init__(parent)
        self.model = model
        tablename = self.model.tableName()
        if(tablename=='DataTypes'):
            self.typename = tablename
        else:
            self.typename = " ".join(tablename.split()[1:])
        self.names = []
        for i in range(self.model.rowCount()):
            self.names.append(self.model.record(i).value(0))
        self.namefield = self.model.record(0).fieldName(0)

        self.setWindowTitle('Add {0}'.format(self.typename))
        grid = QGridLayout(self)
        self.resize(500, 200)

        label = QLabel('New {0}: '.format(self.typename))
        grid.addWidget(label, 0, 0, 1, 1)
        self.typeWidget = QLineEdit()
        self.typeWidget.textEdited.connect(self.reviewText)
        grid.addWidget(self.typeWidget, 0, 1, 1, 4)

        self.warningLabel = QLabel('* {0} already exists.'.format(self.typename))
        self.warningLabel.setAlignment(Qt.AlignCenter)
        self.warningLabel.setStyleSheet('color: red')
        self.warningLabel.hide()
        grid.addWidget(self.warningLabel, 1, 2, 1, 3)

        self.buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        self.buttons.accepted.connect(self.onOk)
        self.buttons.rejected.connect(self.onCancel)
        grid.addWidget(self.buttons, 2, 0, 1, 5)

        self.setLayout(grid)


    @pyqtSlot(str)
    def reviewText(self, text):
        if text in self.names:
            self.warningLabel.show()
        else:
            self.warningLabel.hide()


    @pyqtSlot()
    def onOk(self):
        text = self.typeWidget.text()
        if text in self.names:
            qmb = QMessageBox.critical(self, 'Error!', 'Error: This {0} already exists.'.format(self.typename))
        else:
            self.added.emit(self.typename, text)
            self.close()


    @pyqtSlot()
    def onCancel(self):
        self.close()
